package top.yohann.study.common.service;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.yohann.study.common.common.GlobalException;
import top.yohann.study.common.config.ConstantConfig;
import top.yohann.study.common.util.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Yeung Wah
 * @since 2021/11/21
 */
@Service
public class AliyunService extends BaseService {

    public String uploadFile(MultipartFile file) {
        String endpoint = ConstantConfig.END_POIND;
        String accessKeyId = ConstantConfig.END_KEYID;
        String accessKeySecret = ConstantConfig.END_KEYSECRET;
        String bucketName = ConstantConfig.END_BUCKETNAME;

        //输入流
        InputStream inputStream = null;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //当前文件名
            String fileName = file.getOriginalFilename();
            fileName = fileName.substring(fileName.lastIndexOf("."));

            //随机生成文件名
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //获取日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //最终文件名
            fileName = datePath + "/" + uuid + fileName;

            //获取流数据
            inputStream = file.getInputStream();

            //提交
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //返回URL
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            GlobalException.throwOut("上传失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    public String sendCode(String phone) {
        //在redis中获取验证码
        String code = this.getCode(phone);

        //判断是否一分钟内已发送过
        if (!StringUtils.isEmpty(code)) {
            GlobalException.throwOut(201, code);
        }

        //随机生成验证码
        code = this.generateCode();
        Map<String, Object> param = new HashMap<>(2);
        param.put("code", code);

        boolean isSend = send(param, phone);
        if (isSend) {
            //在redis中存放验证码
            this.setCode(phone, code);
            return code;
        } else {
            GlobalException.throwOut("发送验证码失败！");
        }
        return null;
    }

    private boolean send(Map<String, Object> param, String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }

        String accessKeyId = ConstantConfig.END_KEYID;
        String accessKeySecret = ConstantConfig.END_KEYSECRET;
        String templateCode = ConstantConfig.END_TEMPLATECODE;

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "iEnglish学习平台");
        //模板code
        request.putQueryParameter("TemplateCode", templateCode);
        //验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(param));

        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            Logger.error(e);
            return false;
        }
    }

}